package cn.derry.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author mango
 * @date 2017/12/20
 */
public class CharEncodingFilter implements Filter {

	private static String encoding;

	/**
	 * Default constructor.
	 */
	public CharEncodingFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @author mango
	 * @date 2017/12/20
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @param request
	 * @param response
	 * @param chain
	 * @throws IOException
	 * @throws ServletException
	 * @author mango
	 * @date 2017/12/20
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		request.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
		response.setCharacterEncoding(encoding);
	}

	/**
	 * 
	 * @param fConfig
	 * @throws ServletException
	 * @author mango
	 * @date 2017/12/20
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		String charset = fConfig.getInitParameter("charset");
		if (charset != null && charset.length() != 0) {
			encoding = charset;
			System.out.println("编码拦截器初始化成功 ："+encoding);
		} else {
			throw new ServletException("编码拦截器初始化异常：缺少编码集");
		}
	}

}
